#include "ListNode.h"

LTNode* BuyLTNode(LTDataType x)
{
	LTNode* Newnode = (LTNode*)malloc(sizeof(LTNode));
	if (Newnode == NULL)
	{
		printf("malloc fila\n");
		exit(-1);
	}
	Newnode->data = x;
	Newnode->next = NULL;
	Newnode->prev = NULL;
	return Newnode;
}

LTNode* LTInit()
{
	LTNode* Newnode = BuyLTNode(-1);
	Newnode->next = Newnode;
	Newnode->prev = Newnode;
	return Newnode;
}

void LTprint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	printf("head<->");
	while (cur != phead)
	{
		printf("%d<->",cur->data);
		cur = cur->next;
	}
	printf("head\n");
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

int LTSize(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	int size = 0;
	while (cur != phead)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

void TLPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	//LTNode* NewNode = BuyLTNode(x);
	//LTNode* tail = phead->prev;

	//NewNode->prev = tail;
	//tail->next = NewNode;
	//NewNode->next = phead;
	//phead->prev = NewNode;
	LTInsert(phead, x);
}

void TLPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->prev != phead);
	//LTNode* del = phead->prev;
	//LTNode* delPrev = del->prev;
	//delPrev->next = phead;
	//phead->prev = delPrev;
	//free(del);
	LTErase(phead->prev);
}

void TLPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	//LTNode* NewNode = BuyLTNode(x);
	//LTNode* next = phead->next;

	//NewNode->next = next;
	//next->prev = NewNode;
	//phead->next = NewNode;
	//NewNode->prev = phead;
	LTInsert(phead->next,x);
}

void TLPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	//LTNode* del = phead->next;
	//LTNode* delnext = del->next;
	//phead->next = delnext;
	//delnext->prev = phead;
	//free(del);
	LTErase(phead->next);
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* PosPrev = pos->prev;
	LTNode* NewNode = BuyLTNode(x);
	PosPrev->next = NewNode;
	NewNode->prev = PosPrev;
	pos->prev = NewNode;
	NewNode->next = pos;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* PosPrev = pos->prev;
	LTNode* PosNext = pos->next;
	free(pos);
	PosPrev->next = PosNext;
	PosNext->prev = PosPrev;
}
